import React, { Component } from 'react';
import { getStorage, setStorage } from '../utils/storage';

class TodoListClass extends Component {
  state = {
    //输入框内容
    inputValue: '',
    //列表
    /**
     * {id:1, text:'xxx'}
     */
    list: []
  };

  //增加一项
  addItem() {
    const { inputValue } = this.state;

    this.setState({
      list: setStorage({
        id: new Date().getTime(),
        text: inputValue
      })
    });
  }

  //删除某一项
  removeItem(id) {
    this.setState({
      list: setStorage(null, id)
    });
  }

  //修改输入框内容
  setInputValue(e) {
    //修改state.inputValue就可以修改视图输入框内容
    this.setState({
      inputValue: e.target.value
    });
  }

  //首次加载页面读取localStorage数据
  componentDidMount() {
    this.setState({
      list: getStorage() || []
    });
  }

  render() {
    //1.视图绑定事件
    //2.视图绑定属性
    //3.遍历列表

    const { list } = this.state;

    return (
      <div className="wrapper">
        <div className="input-box">
          <input
            type="text"
            placeholder="请输入待办事项"
            onChange={this.setInputValue.bind(this)}
          ></input>
          <button onClick={this.addItem.bind(this)}>增加</button>
        </div>
        <div className="list-box">
          <ul className="list">
            {list &&
              list.map((item, index) => {
                return (
                  <li key={index}>
                    <span>{item.text}</span>
                    <button onClick={this.removeItem.bind(this, item.id)}>
                      删除
                    </button>
                  </li>
                );
              })}
          </ul>
        </div>
      </div>
    );
  }
}

export default TodoListClass;
